<template>
  <ToolTemplate
    title="JSON 工具"
    description="JSON 格式化、压缩、转换、验证等功能"
  >
    <div class="json-tool">
      <div class="json-editor">
        <textarea
          v-model="inputJson"
          placeholder="请输入 JSON 字符串..."
          @input="handleInput"
        ></textarea>
      </div>
      <div class="actions">
        <button @click="formatJson">格式化</button>
        <button @click="compressJson">压缩</button>
        <button @click="validateJson">验证</button>
        <button @click="copyToClipboard">复制</button>
      </div>
      <div v-if="error" class="error-message">
        {{ error }}
      </div>
    </div>
  </ToolTemplate>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import ToolTemplate from './ToolTemplate.vue'

const inputJson = ref('')
const error = ref('')

const handleInput = () => {
  error.value = ''
}

const formatJson = () => {
  try {
    const obj = JSON.parse(inputJson.value)
    inputJson.value = JSON.stringify(obj, null, 2)
    error.value = ''
  } catch (e) {
    error.value = '无效的 JSON 格式'
  }
}

const compressJson = () => {
  try {
    const obj = JSON.parse(inputJson.value)
    inputJson.value = JSON.stringify(obj)
    error.value = ''
  } catch (e) {
    error.value = '无效的 JSON 格式'
  }
}

const validateJson = () => {
  try {
    JSON.parse(inputJson.value)
    error.value = 'JSON 格式有效'
  } catch (e) {
    error.value = '无效的 JSON 格式'
  }
}

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(inputJson.value)
    error.value = '已复制到剪贴板'
  } catch (e) {
    error.value = '复制失败'
  }
}
</script>

<style scoped lang="scss">
.json-tool {
  display: flex;
  flex-direction: column;
  gap: 20px;

  .json-editor {
    textarea {
      width: 100%;
      height: 400px;
      padding: 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-family: monospace;
      font-size: 14px;
      resize: vertical;

      &:focus {
        outline: none;
        border-color: var(--primary-color);
      }
    }
  }

  .actions {
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border: none;
      background: var(--primary-color);
      color: white;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: var(--hover-color);
      }
    }
  }

  .error-message {
    padding: 10px;
    border-radius: 6px;
    background: #fee2e2;
    color: #dc2626;
    font-size: 14px;
  }
}
</style> 